#include <REGX52.H>
#include "Delay.h"
#include "Nixie.h"
#include "Key.h"
#include "Timer0.h"
#include "I2C.h"
#include "AT24C02.h"

unsigned char KeyNum;
unsigned char Min,Sec,MiniSec;
unsigned char RunFlag;
void main()
{
	Timer0_Init();
	
	while(1)
	{
		KeyNum = Key();
		if(KeyNum==1)//启用暂停按键1
		{
			RunFlag=!RunFlag;
		}
		if(KeyNum==2)
		{
			Min=0;
			Sec=0;
			MiniSec=0;
		}
		
		
		if(KeyNum==3)//写入数据
		{
			AT24C02_WriteByte(0,Min);Delay(5);//0-第一个地址
			AT24C02_WriteByte(1,Sec);Delay(5);//1-第二个地址
			AT24C02_WriteByte(2,MiniSec);Delay(5);//2-第三个地址
		}
		if(KeyNum==4)//读出数据
		{
			Min = AT24C02_ReadByte(0);//读出第一位数据
			
		
			Sec = AT24C02_ReadByte(1);//读出第二位数据
			MiniSec = AT24C02_ReadByte(2);//读出第三位数据
		}
		
		
		Nixie_SetBuf(1,Min/10);
		Nixie_SetBuf(2,Min%10);
		Nixie_SetBuf(3,17);// - (0x40)
		Nixie_SetBuf(4,Sec/10);
		Nixie_SetBuf(5,Sec%10);
		Nixie_SetBuf(6,17);//-
		Nixie_SetBuf(7,MiniSec/10);
		Nixie_SetBuf(8,MiniSec%10);
		
	}
	
}

void Sec_Loop(void)
{
	if(RunFlag)//启用暂停标志位
	{
		MiniSec++;
		if(MiniSec>=100)//1s=1000ms
		{
			MiniSec=0;
			Sec++;
			if(Sec>=60)
			{
				Sec=0;
				Min++;
				if(Min>=60)
					Min=0;
			}
		}
	}
	
	
}


void Timer0_Routine() interrupt 1  //定时器0的中断函数
{
	static unsigned int T0Count1,T0Count2,T0Count3;//多创建几个变量达到定时器复用的效果
	
	TL0 = 0x66;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	
	T0Count1++;
	if(T0Count1>=20)
	{
		//清零重记次
		T0Count1=0;
		Key_Loop();
	}
	
	T0Count2++;
	if(T0Count2>=1)//1ms
	{
		Nixie_Loop();
		T0Count2=0;
	}
	
	T0Count3++;
	if(T0Count3>=10)//10ms
	{
		Sec_Loop();
		T0Count3=0;
	}
	
	
}